package com.ndood.admin.service.system.impl;

import java.util.Date;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import com.ndood.admin.core.web.tools.IdUtils;
import com.ndood.admin.pojo.comm.dto.DataTableDto;
import com.ndood.admin.pojo.system.LogPo;
import com.ndood.admin.pojo.system.StaffPo;
import com.ndood.admin.pojo.system.dto.LogDto;
import com.ndood.admin.pojo.system.query.LogQuery;
import com.ndood.admin.repository.system.LogRepository;
import com.ndood.admin.repository.system.StaffRepository;
import com.ndood.admin.repository.system.manager.LogRepositoryManager;
import com.ndood.admin.service.system.SystemLogService;

import lombok.extern.slf4j.Slf4j;

/**
 * 日志模块业务类
 */
@Service
@Slf4j
public class SystemLogServiceImpl implements SystemLogService {

	@Autowired
	private LogRepositoryManager logRepositoryManager;
	
	@Autowired
	private LogRepository logsDao;
	
	@Autowired
	private StaffRepository staffRepository;
	
	@Autowired
	private IdUtils idUtils;
	
	@Override
	public void makeLog(LogPo log) {
		// Step1: 设置ID
		log.setRecordNo(idUtils.getNextId());
		
		// Step2: 设置用户名
		if(log.getStaffId()!=null) {
			Integer staffId = log.getStaffId();
			Optional<StaffPo> option = staffRepository.findById(staffId);
			if(option.isPresent()) {
				log.setStaffName(option.get().getMobile());
				if(StringUtils.isBlank(log.getStaffName())) {
					log.setStaffName(option.get().getEmail());
				}
			}
		}
		logsDao.save(log);
	}
	
	@Override
	public DataTableDto pageLogList(LogQuery query) throws Exception {

		log.debug("Step1: 封装查询参数"); 
		Integer pageSize = query.getLimit();
		String keywords = query.getKeywords();
		Integer pageNo = query.getPageNo();
		Date startTime = query.getStartTime();
		Date endTime = query.getEndTime();
		
		log.debug("Step2: 分页查询出轮播图数据并返回");
		Page<LogDto> page = logRepositoryManager.pageLogList(keywords, startTime, endTime, pageNo, pageSize);
		return new DataTableDto(page.getContent(), page.getTotalElements());
		
	}
	
}
